<template>
  <div class="home" style="width: 100%; padding: 10px; display: flex; gap: 16px;">
    <!-- 左侧：搜索 + AI分析 + 基本信息 -->
    <div style="flex: 2;">
      <!-- 搜索栏 -->
      <div style="margin: 16px 0; display: flex; gap: 16px; flex-wrap: wrap; align-items: center;">
        <el-input
            clearable
            v-model="search.name"
            placeholder="请输入企业名称"
            style="flex: 1; min-width: 200px;"
            @keyup.enter="load"
        ></el-input>
        <el-input
            clearable
            v-model="search.phone"
            placeholder="请输入统一信用代码"
            style="flex: 1; min-width: 200px;"
            @keyup.enter="load"
        ></el-input>
        <!-- 新增保全金额输入框 -->
        <el-input
            clearable
            v-model="search.preservationAmount"
            placeholder="请输入保全金额（万元）"
            style="flex: 1; min-width: 200px;"
            @keyup.enter="load"
        ></el-input>
        <el-button type="primary" @click="load">查询</el-button>

        <!-- 历史记录按钮 -->
        <el-button type="default" @click="showHistory = !showHistory" style="margin-left: 10px;">
          <i class="el-icon-time"></i> 历史记录
          <span v-if="historyList.length > 0" class="history-badge">{{ historyList.length }}</span>
        </el-button>
      </div>

      <!-- 历史记录面板 -->
      <el-collapse v-model="activeHistoryPanel" v-if="showHistory" style="margin-bottom: 15px;">
        <el-collapse-item title=" 查询历史（点击折叠）" name="1">
          <div v-if="historyList.length === 0" class="empty-history">
            暂无查询历史记录
          </div>
          <el-timeline v-else>
            <el-timeline-item
                v-for="(item, index) in historyList"
                :key="index"
                :timestamp="formatTime(item.time)"
                placement="top"
            >
              <el-card>
                <div class="history-content">
                  <div>企业名称: {{ item.search.name || '未填写' }}</div>
                  <div>统一信用代码: {{ item.search.phone || '未填写' }}</div>
                  <div>保全金额: {{ item.search.preservationAmount ? item.search.preservationAmount + '万元' : '未填写' }}</div>
                </div>
                <div class="history-actions">
                  <el-button
                      size="mini"
                      type="text"
                      @click="loadFromHistory(item.search)"
                  >
                    重新查询
                  </el-button>
                  <el-button
                      size="mini"
                      type="text"
                      class="text-danger"
                      @click="deleteHistory(index)"
                  >
                    删除
                  </el-button>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>

          <el-button
              type="text"
              class="clear-all-history"
              @click="clearAllHistory"
              v-if="historyList.length > 0"
          >
            清除全部历史记录
          </el-button>
        </el-collapse-item>
      </el-collapse>

      <!-- AI智能分析结果展现（逐字打字效果） -->
      <div style="display: flex; align-items: flex-start; margin: 16px 0; gap: 16px;">
        <img src="../../public/ai.png" alt="AI 图标"
             style="width: 64px; height: 64px; opacity: 1; transition: opacity 0.5s ease-in-out;"/>
        <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 8 }"
            clearable
            v-model="typedText"
            placeholder="AI 智能行动指引"
            style="flex: 1; font-size: 14px; border: 1px solid #dcdfe6; border-radius: 4px; padding: 12px;"
        />
      </div>

      <!-- 替换原来的 "企业基本信息" 和 "企业关联人" 两个卡片 -->
      <div style="background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px; margin-bottom: 16px;">
        <!-- 选项卡头部 -->
        <div style="display: flex; border-bottom: 1px solid #e0e0e0; margin-bottom: 15px;">
          <div
              @click="activeTab = 'basicInfo'"
              :style="{
        padding: '8px 16px',
        cursor: 'pointer',
        borderBottom: activeTab === 'basicInfo' ? '2px solid #409eff' : 'none',
        color: activeTab === 'basicInfo' ? '#409eff' : '#666',
        fontWeight: activeTab === 'basicInfo' ? 'bold' : 'normal'
      }"
          >
            企业基本信息
          </div>
          <div
              @click="activeTab = 'relatedPeople'"
              :style="{
        padding: '8px 16px',
        cursor: 'pointer',
        borderBottom: activeTab === 'relatedPeople' ? '2px solid #409eff' : 'none',
        color: activeTab === 'relatedPeople' ? '#409eff' : '#666',
        fontWeight: activeTab === 'relatedPeople' ? 'bold' : 'normal'
      }"
          >
            企业关联人
          </div>
          <div
              @click="activeTab = 'Ab_business'"
              :style="{
        padding: '8px 16px',
        cursor: 'pointer',
        borderBottom: activeTab === 'Ab_business' ? '2px solid #409eff' : 'none',
        color: activeTab === 'Ab_business' ? '#409eff' : '#666',
        fontWeight: activeTab === 'Ab_business' ? 'bold' : 'normal'
      }"
          >
            经营异常信息
          </div>
          <div
              @click="activeTab = 'warnings'"
              :style="{
        padding: '8px 16px',
        cursor: 'pointer',
        borderBottom: activeTab === 'warnings' ? '2px solid #409eff' : 'none',
        color: activeTab === 'warnings' ? '#409eff' : '#666',
        fontWeight: activeTab === 'warnings' ? 'bold' : 'normal'
      }"
          >
            预警提示信息
          </div>
        </div>

        <!-- 选项卡内容 -->
        <div v-show="activeTab === 'basicInfo'">
          <el-table :data="company?.basicInfo ? [company.basicInfo] : []" border style="width: 100%;">
            <el-table-column prop="enterpriseType" label="企业类型"></el-table-column>
            <el-table-column prop="scale" label="企业规模"></el-table-column>
            <el-table-column prop="industry" label="所属行业"></el-table-column>
            <el-table-column prop="establishmentYear" label="成立年份"></el-table-column>
            <el-table-column prop="registrationAddress" label="登记地址"></el-table-column>
            <el-table-column prop="address" label="经营地址"></el-table-column>
            <template #empty>
              <div style="text-align: center; padding: 20px;">暂无数据</div>
            </template>
          </el-table>
        </div>

        <div v-show="activeTab === 'relatedPeople'">
          <el-table :data="relatedPeople" border stripe style="width: 100%;">
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="role" label="角色"></el-table-column>
            <el-table-column prop="phone" label="电话"></el-table-column>
            <el-table-column prop="address" label="地址"></el-table-column>
          </el-table>
        </div>

        <div v-show="activeTab === 'Ab_business'">
          <el-table :data="Ab_business" border stripe style="width: 100%;">
            <el-table-column prop="company_name" label="企业名称"></el-table-column>
            <el-table-column prop="company_id" label="统一社会信用代码/注册号"></el-table-column>
            <el-table-column prop="reason" label="列入事实和理由"></el-table-column>
            <el-table-column prop="date" label="列入日期"></el-table-column>
            <el-table-column prop="id" label="列入文号"></el-table-column>
            <el-table-column prop="department" label="作出决定机关（列入）"></el-table-column>
          </el-table>
        </div>
        <div v-show="activeTab === 'warnings'">
          <el-table :data="warnings" border stripe style="width: 100%;">
            <el-table-column prop="company_name" label="企业名称"></el-table-column>
            <el-table-column prop="company_id" label="统一社会信用代码/注册号"></el-table-column>
            <el-table-column prop="reason" label="预警原因"></el-table-column>
            <el-table-column prop="date" label="实施预警日期"></el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 关联案件信息板块 -->
      <div style="background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px; margin-bottom: 16px;">
        <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">关联案件信息</h3>

        <!-- 执行/审判分栏 -->
        <el-tabs v-model="activeCaseTab">
          <el-tab-pane label="执行" name="execution">
            <el-table :data="caseData.execution" border stripe style="width: 100%;">
              <el-table-column prop="caseNumber" label="案号"></el-table-column>
              <el-table-column prop="parties" label="当事人"></el-table-column>
              <el-table-column prop="amount" label="标的额" :formatter="formatCaseAmount"></el-table-column>
              <el-table-column prop="closeMethod" label="结案方式"></el-table-column>
              <template #empty>
                <div style="text-align: center; padding: 20px; color: #909399;">暂无执行案件数据</div>
              </template>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="审判" name="trial">
            <el-table :data="caseData.trial" border stripe style="width: 100%;">
              <el-table-column prop="caseNumber" label="案号"></el-table-column>
              <el-table-column prop="parties" label="当事人"></el-table-column>
              <el-table-column prop="amount" label="标的额" :formatter="formatCaseAmount"></el-table-column>
              <el-table-column prop="closeMethod" label="结案方式"></el-table-column>
              <template #empty>
                <div style="text-align: center; padding: 20px; color: #909399;">暂无审判案件数据</div>
              </template>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 股东案件信息板块 -->
      <div style="background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px; margin-bottom: 16px;">
        <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">股东案件信息</h3>

        <el-tabs v-model="activeShareholderCaseTab">
          <el-tab-pane label="股东执行案件" name="shareholderExecution">
            <el-table :data="shareholderCaseData.execution" border stripe style="width: 100%;">
              <el-table-column prop="caseNumber" label="案号"></el-table-column>
              <el-table-column prop="parties" label="当事人"></el-table-column>
              <el-table-column prop="amount" label="标的额" :formatter="formatCaseAmount"></el-table-column>
              <el-table-column prop="closeMethod" label="结案方式"></el-table-column>
              <template #empty>
                <div style="text-align: center; padding: 20px; color: #909399;">暂无股东执行案件数据</div>
              </template>
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="股东审判案件" name="shareholderTrial">
            <el-table :data="shareholderCaseData.trial" border stripe style="width: 100%;">
              <el-table-column prop="caseNumber" label="案号"></el-table-column>
              <el-table-column prop="parties" label="当事人"></el-table-column>
              <el-table-column prop="amount" label="标的额" :formatter="formatCaseAmount"></el-table-column>
              <el-table-column prop="closeMethod" label="结案方式"></el-table-column>
              <template #empty>
                <div style="text-align: center; padding: 20px; color: #909399;">暂无股东审判案件数据</div>
              </template>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>


      <!-- 贡献维度（税收）与财务与社保缴纳 并排 -->
      <div style="display: flex; gap: 16px; margin-bottom: 16px;">
        <!-- 贡献维度（税收） -->
        <div
            style="flex: 1; background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px;">
          <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px; text-align: center; color: #67c23a;">
            贡献维度（税收）
          </h3>
          <div ref="contributionChart" style="width: 100%; min-height: 180px;"></div>
          <div style="font-size: 12px; color: #666; margin-top: 15px;">
            <p style="margin: 6px 0;">2022年：{{ company?.contributionDimension?.taxPaid?.year2022 }}
              亿元 </p>
            <p style="margin: 6px 0;">2023年：{{ company?.contributionDimension?.taxPaid?.year2023}}
              亿元</p>
            <p style="margin: 6px 0;">2024年：{{ company?.contributionDimension?.taxPaid?.year2024}}
              亿元</p>
          </div>

          <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px; text-align: center; color: #409eff;">
            社保缴纳情况
          </h3>
          <div ref="socialSecurityChart" style="width: 100%; min-height: 180px;"></div>
          <div style="font-size: 12px; color: #666; margin-top: 15px;">
            <p style="margin: 6px 0;">2022年：{{ company?.socialSecurity?.year2022?.total }} 人</p>
            <p style="margin: 6px 0;">2023年：{{ company?.socialSecurity?.year2023?.total }} 人</p>
            <p style="margin: 6px 0;">2024年：{{ company?.socialSecurity?.year2024?.total}} 人</p>
          </div>
        </div>

      </div>
    </div>

    <!-- 右侧：图表和资产信息（与AI打字框对齐） -->
    <div style="flex: 1; display: flex; flex-direction: column; gap: 16px;">
      <!-- 企业信用评估打分、履行能力打分 -->
      <div style="background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px;">
        <div style="display: flex; gap: 30px;">
          <!-- 信用评估打分 -->
          <div style="flex: 1; text-align: center;">
            <div style="font-size: 24px; font-weight: bold; color: #0066cc;">{{ creditScore || '暂无数据' }}</div>
            <div style="color: #666; margin: 8px 0;">企业信用评估</div>
            <div
                style="width: 100%; height: 10px; background: #e0e0e0; border-radius: 5px; overflow: hidden; margin-top: 8px;"
            >
              <div
                  :style="{
                  height: '100%',
                  background: 'linear-gradient(to right, #4CAF50, #FFC107, #F44336)',
                  width: creditScore ? `${creditScore}%` : '0%',
                  transition: 'width 0.5s ease'
                }"
              ></div>
            </div>
            <div style="color: #333; font-size: 12px; margin-top: 8px;">
              {{ getCreditLevel(creditScore) }}
            </div>
          </div>

          <!-- 履行能力打分 -->
          <div style="flex: 1; text-align: center;">
            <div style="font-size: 24px; font-weight: bold; color: #0066cc;">{{ performanceScore || '暂无数据' }}</div>
            <div style="color: #666; margin: 8px 0;">履行能力评估</div>
            <div
                style="width: 100%; height: 10px; background: #e0e0e0; border-radius: 5px; overflow: hidden; margin-top: 8px;"
            >
              <div
                  :style="{
                  height: '100%',
                  background: 'linear-gradient(to right, #4CAF50, #FFC107, #F44336)',
                  width: performanceScore ? `${performanceScore}%` : '0%',
                  transition: 'width 0.5s ease'
                }"
              ></div>
            </div>
            <div style="color: #333; font-size: 12px; margin-top: 8px;">
              {{ getPerformanceLevel(performanceScore) }}
            </div>
          </div>
        </div>
      </div>

      <!-- 名下资产状况（2024年） -->
      <div style="background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px;">
        <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">名下资产状况</h3>
        <div ref="pieChart" style="width: 100%; min-height: 200px;"></div>
      </div>

      <!-- 经营状况 -->
      <div style="background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px;">
        <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">经营状况</h3>
        <div class="status-card" :class="getStatusClass(company?.basicInfo?.status)"
             style="text-align: center; padding: 15px;">
          {{ company?.basicInfo?.status || '暂无数据' }}
        </div>
      </div>

      <!-- 新增：用电数据 -->
      <div style="background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px;">
        <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">用电数据</h3>
        <el-table :data="electricityUsage || []" border style="width: 100%;">
          <el-table-column prop="yearMonth" label="月份"></el-table-column>
          <el-table-column prop="totalPower" label="用电量（度）"></el-table-column>
          <el-table-column prop="receivedAmount" label="费用（元）"></el-table-column>
        </el-table>
        <el-pagination
            v-if="company?.electricityUsage && company.electricityUsage.length > 10"
            background
            layout="prev, pager, next, jumper, total"
            :page-size="10"
            :total="company?.electricityUsage.length || 0"
            style="margin-top: 15px; text-align: right;"
        />
      </div>


      <!-- 资产状况 -->
      <div style="background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px;">
        <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">资产状况</h3>
        <el-table :data="company?.assetDistribution || []" border style="width: 100%;">
          <el-table-column prop="name" label="资产类别"></el-table-column>
          <el-table-column prop="value" label="金额（元）" :formatter="formatValue"></el-table-column>
        </el-table>
      </div>
      <!-- 备忘录信息抓取 -->
      <div style="height: 290px; background: white; border-radius: 8px; box-shadow: 0 2px 12px rgba(0,0,0,0.1); padding: 20px;">
        <h3 style="margin: 0 0 15px 0; color: #333; font-size: 16px;">信息补录</h3>
        <div style="padding: 15px;">
          <div style="margin-bottom: 15px;">
            <h4 style="margin-top: 0;">补录提醒</h4>
            <div style="display: flex; flex-wrap: wrap; gap: 10px;">
              <el-tag
                  v-for="tag in reminderTags"
                  :key="tag.type"
                  :type="tag.type"
                  size="small"
                  @click="openMemoDialogWithTag(tag.label)"
                  style="cursor: pointer;"
              >
                {{ tag.label }}
              </el-tag>
            </div>
          </div>
          <div style="text-align: center;">
            <el-button type="primary" plain @click="supplementDialogVisible = true" style="font-size: 30px; padding: 12px 24px;width: 100%;height: 60px">
              <i class="el-icon-edit"></i>
              补录
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 鱼骨图组件 -->
  <el-card class="mb-3">
    <template #header>
      <div class="card-header">
        <span>企业信息鱼骨图分析</span>
        <el-button
            type="primary"
            @click="toggleFishbone"
            size="big"
            style="float: right;"
        >
          {{ showFishbone ? '收起' : '展开' }}鱼骨图
        </el-button>
      </div>
    </template>
    <div v-show="showFishbone" style="margin-top: 20px;">
      <FishboneDiagram
          :id-number="search.phone"
          :name="search.name"
          :isQuery = "isQuery"
      />
    </div>
  </el-card>
  <EnterpriseInfoSupplement v-model:visible="supplementDialogVisible" />
</template>

<script>
import { ref } from 'vue';
import { getCompanyData } from "@/mock/data.js";
import * as echarts from 'echarts';
import router from "@/router";
import FishboneDiagram from './Tableyugucompany.vue'; // 引入鱼骨图组件
import EnterpriseInfoSupplement from '@/components/EnterpriseInfoSupplement.vue';
import { getCompanyElectricityData } from '@/scripts/getCompanyElectricity';

export default {
  name: "CompanySearch",
  components: {
    FishboneDiagram, // 注册鱼骨图组件
    EnterpriseInfoSupplement
  },
  data() {
    return {
      supplementDialogVisible: false,
      isQuery: false,
      search: {
        name: "",
        phone: "",
        preservationAmount: "",
        hasSearched: false
      },
      activeTab: 'basicInfo', // 'basicInfo' 或 'relatedPeople'
      activeCaseTab: 'execution', // 'execution' 或 'trial'
      // 添加关联案件数据
      caseData: {
        execution: [], // 执行案件
        trial: []     // 审判案件
      },
      activeShareholderCaseTab: 'shareholderExecution', // 'shareholderExecution' 或 'shareholderTrial'
      shareholderCaseData: {
        execution: [], // 股东执行案件
        trial: []     // 股东审判案件
      },
      electricityUsage: [],
      socialSecurityChart: null, // 新增社保图表引用
      company: null,
      relatedPeople: [],
      Ab_business:[],
      warnings: [],
      assets: [],
      typedText: "",
      creditScore: null,
      performanceScore: null,
      pieChart: null,
      contributionChart: null,
      financialChart: null,
      typingInterval: null,
      showFishbone: true, // 控制鱼骨图显示/隐藏状态
      
      // 历史记录相关
      historyList: [],
      showHistory: false,
      activeHistoryPanel: ['1']
    };
  },
  mounted() {
    this.initCharts();
    // 监听窗口大小变化，重新调整图表大小
    window.addEventListener('resize', this.handleResize);

    // 从localStorage加载历史记录
    this.loadHistoryFromStorage();
  },
  beforeDestroy() {
    if (this.pieChart) this.pieChart.dispose();
    if (this.contributionChart) this.contributionChart.dispose();
    if (this.socialSecurityChart) this.socialSecurityChart.dispose();
    if (this.typingInterval) clearInterval(this.typingInterval);
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    openMemoDialog() {
      this.supplementDialogVisible = true;
    },
    // 格式化案件标的额
    formatCaseAmount(row, column) {
      const value = row.amount;
      if (value >= 1e8) {
        return (value / 1e8).toFixed(2) + '亿元';
      } else if (value >= 1e4) {
        return (value / 1e4).toFixed(2) + '万元';
      }
      return value + '元';
    },

    // 切换鱼骨图显示/隐藏
    toggleFishbone() {
      this.showFishbone = !this.showFishbone;
    },

    goToHome() {
      router.push({name: 'manage1'});
    },

    initCharts() {
      this.pieChart = echarts.init(this.$refs.pieChart);
      this.contributionChart = echarts.init(this.$refs.contributionChart);
      this.socialSecurityChart = echarts.init(this.$refs.socialSecurityChart);
    },

    // 处理窗口大小变化，让图表自适应
    handleResize() {
      if (this.pieChart) this.pieChart.resize();
      if (this.contributionChart) this.contributionChart.resize();
      if (this.socialSecurityChart) this.socialSecurityChart.resize();
    },

    updateCharts() {
      // 更新饼图（2024年资产分布）
      if (this.pieChart && this.company?.assetDistribution) {
        const assetData = this.company.assetDistribution.map(item => ({
          name: item.name,
          value: item.value
        }));
        const pieOption = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} 元 ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'middle',
            textStyle: {
              fontSize: 12
            }
          },
          series: [
            {
              name: '资产分布（2024）',
              type: 'pie',
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '16',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              data: assetData
            }
          ]
        };
        this.pieChart.setOption(pieOption);
      }

      // 更新贡献维度图表（税收趋势）
      if (this.contributionChart) {
        const taxData = [
          {year: '2022', value: this.company?.contributionDimension?.taxPaid?.year2022 || 0},
          {year: '2023', value: this.company?.contributionDimension?.taxPaid?.year2023 || 0},
          {year: '2024', value: this.company?.contributionDimension?.taxPaid?.year2024 || 0}
        ];

        const contributionOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'line'
            },
            formatter: (params) => {
              let result = `${params[0].name}<br/>`;
              params.forEach(param => {
                result += `${param.marker}${param.seriesName}: ${param.value} 亿元<br/>`;
              });
              return result;
            }
          },
          xAxis: {
            type: 'category',
            data: taxData.map(d => d.year),
            axisLabel: {
              fontSize: 12,
              margin: 10
            }
          },
          yAxis: {
            type: 'value',
            name: '亿元',
            axisLabel: {
              fontSize: 14,
              margin: 20
            },
            axisTick: {
              alignWithLabel: true
            },
            splitNumber: 2,
            max: 0.3,
            min: 0.1,
            interval: 0.1,
            splitLine: {
              show: false
            },
            formatter: (value) => {
              return value + ' 亿元';
            }
          },
          series: [{
            name: '税收贡献',
            type: 'line',
            smooth: true,
            areaStyle: {opacity: 0.3},
            lineStyle: {width: 2},
            symbolSize: 6,
            data: taxData.map(d => d.value)
          }]
        };
        this.contributionChart.setOption(contributionOption);
      }


      // 更新社保缴纳情况图表
      if (this.socialSecurityChart && this.company?.socialSecurity) {
        const socialSecurityData = [
          {
            year: '2022',
            total: this.company.socialSecurity.year2022?.total || 0,
            pension: this.company.socialSecurity.year2022?.pension || 0,
            medical: this.company.socialSecurity.year2022?.medical || 0,
            unemployment: this.company.socialSecurity.year2022?.unemployment || 0
          },
          {
            year: '2023',
            total: this.company.socialSecurity.year2023?.total || 0,
            pension: this.company.socialSecurity.year2023?.pension || 0,
            medical: this.company.socialSecurity.year2023?.medical || 0,
            unemployment: this.company.socialSecurity.year2023?.unemployment || 0
          },
          {
            year: '2024',
            total: this.company.socialSecurity.year2024?.total || 0,
            pension: this.company.socialSecurity.year2024?.pension || 0,
            medical: this.company.socialSecurity.year2024?.medical || 0,
            unemployment: this.company.socialSecurity.year2024?.unemployment || 0
          }
        ];

        const socialSecurityOption = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'line'
            },
            formatter: (params) => {
              let result = `${params[0].name}<br/>`;
              params.forEach(param => {
                result += `${param.marker}${param.seriesName}: ${param.value} 人<br/>`;
              });
              return result;
            }
          },
          legend: {
            data: ['总人数', '养老保险', '医疗保险', '失业保险'],
            textStyle: { fontSize: 10 },
            bottom: 5,
            itemWidth: 12,
            itemHeight: 8,
            itemGap: 5
          },
          grid: {
            top: '15%',
            left: '3%',
            right: '3%',
            bottom: '15%',
            containLabel: true
          },
          xAxis: {
            type: 'category',
            data: socialSecurityData.map(d => d.year),
            axisLabel: {
              fontSize: 10,
              margin: 8
            }
          },
          yAxis: {
            type: 'value',
            name: '人数',
            nameTextStyle: {
              fontSize: 10
            },
            axisLabel: {
              fontSize: 10,
              margin: 8
            },
            splitNumber: 4
          },
          series: [
            {
              name: '总人数',
              type: 'line',
              data: socialSecurityData.map(d => d.total),
              smooth: true,
              symbolSize: 6,
              lineStyle: { width: 2 }
            },
            {
              name: '养老保险',
              type: 'line',
              data: socialSecurityData.map(d => d.pension),
              smooth: true,
              symbolSize: 4,
              lineStyle: { width: 1 }
            },
            {
              name: '医疗保险',
              type: 'line',
              data: socialSecurityData.map(d => d.medical),
              smooth: true,
              symbolSize: 4,
              lineStyle: { width: 1 }
            },
            {
              name: '失业保险',
              type: 'line',
              data: socialSecurityData.map(d => d.unemployment),
              smooth: true,
              symbolSize: 4,
              lineStyle: { width: 1 }
            }
          ]
        };
        this.socialSecurityChart.setOption(socialSecurityOption);
      }
    },

    // 计算信用评分
    calculateCreditScore() {
      if (!this.company) return null;

      const financial = this.company.financialAndExecution;
      if (!financial) return null;

      // 获取最新的财务数据（2024年）
      const asset = financial.assetStatus?.year2024 || 0;
      const revenue = financial.revenue?.year2024 || 0;
      const liability = financial.liabilities || 0;

      // 根据规则计算评分
      if (asset + revenue > liability) {
        const ratio = (asset + revenue) / (liability > 0 ? liability : 1);
        if (ratio > 2) return 85;
        if (ratio > 1.5) return 80;
        return 75;
      } else {
        const diff = (asset + revenue) - liability;
        if (diff > -5) return 65;
        if (diff > -10) return 60;
        return 50;
      }
    },

    // 获取信用等级
    getCreditLevel(score) {
      if (!score) return '暂无数据';
      if (score >= 80) return '优秀';
      if (score >= 70) return '良好';
      if (score >= 60) return '一般';
      if (score >= 50) return '较差';
      return '差';
    },

    // 获取履行能力等级
    getPerformanceLevel(score) {
      if (!score) return '暂无数据';
      if (score >= 80) return '强';
      if (score >= 70) return '较强';
      if (score >= 60) return '中等';
      if (score >= 50) return '较弱';
      return '弱';
    },

    // 获取经营状态样式类
    getStatusClass(status) {
      switch (status) {
        case '在业':
          return 'status-normal';
        case '停业':
          return 'status-closed';
        case '注销':
          return 'status-cancelled';
        default:
          return 'status-default';
      }
    },

    // 打字动画
    typeText(text) {
      this.typedText = "";
      let index = 0;
      this.typingInterval = setInterval(() => {
        if (index < text.length) {
          this.typedText += text.charAt(index);
          index++;
        } else {
          clearInterval(this.typingInterval);
        }
      }, 50);
    },

    // 格式化金额显示
    formatValue(row, column) {
      const value = row.value;
      if (value >= 1e8) {
        return (value / 1e8).toFixed(2) + '亿';
      } else if (value >= 1e4) {
        return (value / 1e4).toFixed(2) + '万';
      }
      return value.toString();
    },

    async load() {
      const company = getCompanyData({ name: this.search.name, creditCode: this.search.phone });
      this.hasSearched = true;
      this.isQuery = !this.isQuery;
      console.log("状态：",this.isQuery)
      if (company) {
        this.company = {
          creditCode: company.creditCode,
          name: company.name,
          suggestion: company.suggestion,
          basicInfo: company.basicInfo,
          shareholders: company.shareholders,
          assetDistribution: company.assetDistribution,
          contributionDimension: company.contributionDimension,
          financialAndExecution: company.financialAndExecution,
          creditScore: company.creditScore,
          performanceScore: company.performanceScore,
          socialSecurity: company.socialSecurity
        };

        this.relatedPeople = company.shareholders || [];
        this.Ab_business = company.Ab_business || [];
        this.warnings = company.warnings || [];
        // 初始化关联案件数据 - 直接使用模拟数据中的案件
        this.caseData = {
          execution: company.executionCases || [],
          trial: company.trialCases || []
        };

        // 初始化股东案件数据
        this.shareholderCaseData = {
          execution: company.shareholderExecutionCases || [],
          trial: company.shareholderTrialCases || []
        };

        // 使用动态计算的信用评分
        this.creditScore = this.calculateCreditScore();
        // 履行能力评分仍使用原数据
        this.performanceScore = company.performanceScore;

        // 根据保全金额判断输出内容
        if (this.search.preservationAmount && this.search.preservationAmount.trim() !== "") {
          // 有保全金额输入时，进行反担保评估
          if(this.search.preservationAmount > 0)
            this.typeText( "该公司具备良好的经营条件和资信状况，可以考虑采取反担保灵活保全等执行措施。");
          else
            this.typeText( "该公司不具备反担保条件，需要考虑其他保全方案或执行转破产程序。");
        } else {
          // 无保全金额输入时，进行企业评估（执转破）
          this.typeText(company.suggestion || "该公司具备良好的经营条件和资信状况，可以考虑采取反担保灵活保全等执行措施。");
        }

        // 更新图表
        this.$nextTick(() => {
          this.updateCharts();
          // 图表更新后调整大小
          this.handleResize();
        });
      } else {
        this.company = null;
        this.relatedPeople = [];
        this.assets = [];
        this.creditScore = null;
        this.performanceScore = null;
        this.caseData = { execution: [], trial: [] };
        this.shareholderCaseData = { execution: [], trial: [] };

        // 查询失败时也根据保全金额判断输出
        if (this.search.preservationAmount && this.search.preservationAmount.trim() !== "") {
          this.typeText( "未查询到相关企业信息，无法进行反担保评估。请检查输入的企业名称或统一信用代码是否正确。");
        } else {
          this.typeText( "未查询到相关企业信息，请检查输入的企业名称或统一信用代码是否正确。");
        }
      }
      
      this.electricityUsage = getCompanyElectricityData({ name: this.company.name });


      // 如果有有效的查询条件，保存到历史记录
      if (this.search.name || this.search.phone) {
        this.saveToHistory();
      }
    },

    // 保存查询条件到历史记录
    saveToHistory() {
      // 深拷贝查询条件，避免引用问题
      const searchData = JSON.parse(JSON.stringify(this.search));

      // 检查是否和上一条记录相同，避免重复保存
      const lastRecord = this.historyList[0];
      if (lastRecord &&
          lastRecord.search.name === searchData.name &&
          lastRecord.search.phone === searchData.phone) {
        return;
      }

      // 创建历史记录项
      const historyItem = {
        search: searchData,
        time: new Date().getTime() // 记录时间戳
      };

      // 添加到历史列表开头
      this.historyList.unshift(historyItem);

      // 限制历史记录数量，最多保存20条
      if (this.historyList.length > 20) {
        this.historyList.pop();
      }

      // 保存到localStorage
      this.saveHistoryToStorage();
    },

    // 从localStorage加载历史记录
    loadHistoryFromStorage() {
      const savedHistory = localStorage.getItem('companyQueryHistory');
      if (savedHistory) {
        try {
          this.historyList = JSON.parse(savedHistory);
        } catch (e) {
          console.error('Failed to parse history from localStorage', e);
          localStorage.removeItem('companyQueryHistory');
        }
      }
    },

    // 保存历史记录到localStorage
    saveHistoryToStorage() {
      localStorage.setItem('companyQueryHistory', JSON.stringify(this.historyList));
    },

    // 从历史记录加载查询条件并执行查询
    loadFromHistory(searchData) {
      this.search = JSON.parse(JSON.stringify(searchData));
      this.load();
    },

    // 删除单条历史记录
    deleteHistory(index) {
      this.historyList.splice(index, 1);
      this.saveHistoryToStorage();
    },

    // 清除所有历史记录
    clearAllHistory() {
      this.$confirm('确定要清除所有查询历史记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.historyList = [];
        this.saveHistoryToStorage();
        this.$message({
          type: 'success',
          message: '已清除所有历史记录'
        });
      }).catch(() => {
        // 用户取消操作
      });
    },

    // 格式化时间显示
    formatTime(timestamp) {
      const date = new Date(timestamp);
      return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
    }
  }
};
</script>

<style scoped>
.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.el-form-item {
  margin-bottom: 12px;
}

.el-tag {
  padding: 8px 16px;
  font-size: 14px;
}

/* 添加状态卡片样式 */
.status-card {
  border-radius: 4px;
  padding: 10px;
  text-align: center;
}

.status-normal {
  background-color: #f0f9ff;
  color: #409eff;
  border: 1px solid #409eff;
}

.status-closed {
  background-color: #fdf6ec;
  color: #e6a23c;
  border: 1px solid #e6a23c;
}

.status-cancelled {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #f56c6c;
}

.status-default {
  background-color: #f4f4f5;
  color: #909399;
  border: 1px solid #909399;
}

/* 鱼骨图卡片样式 */
.mb-3 {
  margin: 16px 10px;
  width: calc(100% - 20px);
}

/* 历史记录样式 */
.history-badge {
  display: inline-block;
  background-color: #1890ff;
  color: white;
  border-radius: 10px;
  padding: 0 6px;
  font-size: 12px;
  margin-left: 5px;
}

.el-timeline {
  padding: 10px 0;
}

.el-timeline-item {
  margin-bottom: 15px;
}

.history-content {
  margin-bottom: 10px;
  font-size: 14px;
}

.history-content > div {
  margin-bottom: 4px;
}

.history-actions {
  text-align: right;
  margin-top: 5px;
}

.empty-history {
  text-align: center;
  padding: 20px;
  color: #909399;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.clear-all-history {
  color: #f56c6c;
  margin-top: 10px;
  display: block;
  text-align: center;
}
</style>